const crypto = require('crypto');
const query = require('../models'); // 引入某某文件夹下的 index.js 可以省略不写 index.js
const createRandom = require('../utils/createRandom');

module.exports = {
  login(req, res) {
    console.log('收到用户登录请求：', req.body);
    const { username, password } = req.body;


    const sql = 'SELECT * FROM chat_room_user WHERE user_name=?';
    query(sql, [username])
      .then(result => {
        console.log('登录：', result);
        console.log(result[0].user_pass);

        if (result.length === 0) {
          res.json({
            code: '1001',
            msg: '账号或者密码错误'
          });
        } else {

          const random = result[0].user_pass.substr(0, 12);

          // 加密
          const md5 = crypto.createHash("md5");
          const md5Password = md5.update(password).digest("hex");
          console.log('加密后：', md5Password);

          if (result[0].user_pass == random + md5Password) {
            req.session.sign = true;

            res.json({
              code: '200',
              msg: '登陆成功',
              data: {
                userId: result[0].user_id,
                avator: '127.0.0.1:3000' + result[0].avator,
              }
            });
          } else {
            res.json({
              code: '1001',
              msg: '账号或者密码错误'
            });
          }

        }
      })
      .catch((err) => {
        res.json({
          code: '1002',
          msg: '服务器出错',
          err
        })
      })

  },
  verify(req, res) {
    const { username } = req.query;
    const sql = 'SELECT * FROM chat_room_user WHERE user_name=?';

    query(sql, [username])
      .then(result => {
        if (result.length >= 1) {
          res.json({
            code: '1003',
            msg: '账号存在'
          })
        } else {
          res.json({
            code: '200',
            msg: '可以使用'
          });
        }
      })
      .catch(err => {
        res.json({
          code: '1002',
          msg: '服务器出错',
          err
        })
      })
  },
  register(req, res) {
    const { username, password, email } = req.body;
    console.log('接收到密码：', password);
    const random = createRandom(false, 12);
    console.log('随机数：', random);

    // 加密
    const md5 = crypto.createHash("md5");
    const md5Password = md5.update(password).digest("hex");
    console.log('加密后：', md5Password);

    const finalPassword = random + md5Password;
    console.log('存入数据库密码：', finalPassword, finalPassword.length);

    const sql = `INSERT INTO chat_room_user VALUE(NULL,?,?,?,DEFAULT,'',DEFAULT)`;

    query(sql, [username, finalPassword, email])
      .then(result => {
        res.json({
          code: '200',
          msg: '注册成功'
        })
      })
      .catch(err => {
        res.json({
          code: '1002',
          msg: '服务器出错',
          err
        })
      })
  },
  quit(req, res) {
    req.session.sign = false;
    res.json({
      code: '200',
      msg: '退出成功'
    });
  }
}